<template>
  <div class="statistics-box">
    <div class="renew-time">更新倒计时：{{ times }}s</div>
    <!-- 1 -->
    <div class="item-box" v-loading="t1loading">
      <div class="statistics-top">
        <div class="statistics-left">
          <div class="search-box">
            <div class="search-flex">
              <div class="search-label">年份查询</div>
              <div class="search-item">
                <el-date-picker class="search-input" value-format="yyyy" :picker-options="pickerOptions" v-model="year"
                  type="year" placeholder="选择年" @change="yearChange">
                </el-date-picker>
              </div>
            </div>
            <div class="search-flex" v-if="[10, 1].includes(userInfo.position_id)">
              <div class="search-label">客户经理</div>
              <div class="search-item">
                <el-select filterable class="search-input" v-model="user_manage" clearable placeholder="选择客户经理"
                  @change="userChange">
                  <el-option v-for="(item, idx) in userManageList" :key="idx" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </div>
            </div>
          </div>
          <div class="card-statistics">
            <div class="card-title">签约项目数</div>
            <div class="card-number"><i class="iconfont icon-dingdan"></i>{{ t1Data.TotalNumberOfSignedProjects }}</div>
          </div>
          <div class="card-statistics">
            <div class="card-title">合同签约总额(元)</div>
            <div class="card-number"><i class="iconfont icon-shangjinjine"></i>{{ t1Data.TotalContractAmount }}</div>
          </div>
        </div>
        <div class="statistics-right">
          <div class="statistics-tips">
            <span class="title">月度签约项目数</span>
          </div>
          <div class="ydqyxms" ref="ydqyxms"></div>
        </div>
      </div>
      <el-divider></el-divider>
      <div class="statistics-bottom">
        <div class="statistics-tips">
          <span class="title">月度签约金额趋势</span>
        </div>
        <div class="conversion">1k=1000元</div>
        <div class="ydqyjeqs" ref="ydqyjeqs"></div>
      </div>
    </div>
    <!-- 2 -->
    <div class="item-box" v-loading="t2loading">
      <div class="statistics-tips">
        <span class="title">实时项目汇总</span>
      </div>
      <el-table :data="tableData1" max-height="300" :summary-method="getSummaries" show-summary
        :header-cell-style="{ background: '#FAFBFC', color: '#828A9D', textAlign: 'center' }"
        :cell-style="{ textAlign: 'center', color: '#1B2431' }">
        <el-table-column prop="account_manager_name" label="客户经理" show-overflow-tooltip></el-table-column>
        <el-table-column prop="ToBeStarted" label="待启动"></el-table-column>
        <el-table-column prop="WaitForSurveySite" label="待勘场"></el-table-column>
        <el-table-column prop="SurveySiteMapping" label="待勘场出图"></el-table-column>
        <el-table-column prop="ProducingDesignDrawings" label="待方案设计"></el-table-column>
        <el-table-column prop="ToBeQuoted" label="待报价"></el-table-column>
        <el-table-column prop="InNegotiations" label="洽谈中"></el-table-column>
        <el-table-column prop="SignedContract" label="已签约"></el-table-column>
        <el-table-column prop="ToBeSettled" label="待结算"></el-table-column>
      </el-table>
    </div>
    <!-- 3 -->
    <div class="item-box" v-loading="t3loading">
      <div class="statistics-tips">
        <span class="title">签约情况统计</span>

        <div class="search-box">
          <div class="search-flex">
            <div class="search-label">日期查询</div>
            <div class="search-item">
              <el-date-picker v-model="time" value-format="yyyy-MM-dd" class="search-input2" type="daterange"
                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions"
                @change="timeChange">
              </el-date-picker>
            </div>
          </div>
        </div>
      </div>
      <el-table :data="tableData2" :header-cell-style="{ background: '#FAFBFC', color: '#828A9D', textAlign: 'center' }"
        :cell-style="{ textAlign: 'center', color: '#1B2431' }">
        <el-table-column prop="TotalContractAmount" label="合同签约总额"></el-table-column>
        <el-table-column prop="AverageAmountPerOrder" label="单均金额"></el-table-column>
        <el-table-column prop="NumberOfContractedProjects" label="签约项目数"></el-table-column>
        <el-table-column prop="NumberOfCirculationProjects" label="流转项目数"></el-table-column>
        <el-table-column prop="NumberOfNewProjectsAdded" label="新增项目数"></el-table-column>
        <el-table-column prop="NumberOfCancelledProjects" label="取消项目数"></el-table-column>
        <el-table-column prop="StatisticalSigningRate" label="签约率">
          <template slot-scope="scope">{{ scope.row.StatisticalSigningRate }}%</template>
        </el-table-column>
        <el-table-column prop="StatisticalDiscountRate" label="折扣率">
          <template slot-scope="scope">{{ scope.row.StatisticalDiscountRate }}%</template>
        </el-table-column>
        <el-table-column prop="ProjectSettlementAmount" label="项目结算数"></el-table-column>
      </el-table>
      <el-divider></el-divider>
      <div class="statistics-tips">
        <span class="title">各类型门店签约情况统计</span>
      </div>
      <el-table :data="tableData3"
        :summary-method="(param) => { return getSummaries(param, '各类型门店签约情况统计', [2, 6, 7, 8]) }" show-summary
        :header-cell-style="{ background: '#FAFBFC', color: '#828A9D', textAlign: 'center' }"
        :cell-style="{ textAlign: 'center', color: '#1B2431' }">
        <el-table-column prop="project_type_name" label="门店类型"></el-table-column>
        <el-table-column prop="ProjectTypeTotalContractAmount" label="合同签约总额"></el-table-column>
        <el-table-column prop="ProjectTypeProportionSignedAmount" label="签约金额占比">
          <template slot-scope="scope">{{ scope.row.ProjectTypeProportionSignedAmount }}%</template>
        </el-table-column>
        <el-table-column prop="ProjectTypeAverageAmountPerOrder" label="单均金额"></el-table-column>
        <el-table-column prop="ProjectTypeNumberOfContractedProjects" label="签约项目数"></el-table-column>
        <el-table-column prop="ProjectTypeNumberOfCancelledProjects" label="取消项目数"></el-table-column>
        <el-table-column prop="ProjectTypeStatisticalSigningRate" label="签约率">
          <template slot-scope="scope">{{ scope.row.ProjectTypeStatisticalSigningRate }}%</template>
        </el-table-column>
        <el-table-column prop="ProjectTypeSigningTimeLimit" label="签约时效(天)"></el-table-column>
        <el-table-column prop="ProjectTypeStatisticalDiscountRate" label="折扣率">
          <template slot-scope="scope">{{ scope.row.ProjectTypeStatisticalDiscountRate }}%</template>
        </el-table-column>
        <el-table-column prop="ProjectTypeProjectSettlementAmount" label="项目结算数"></el-table-column>
      </el-table>
      <el-divider></el-divider>
      <div class="flex">
        <div style="width: calc(100% - 400px);">
          <div class="statistics-tips">
            <span class="title">客户经理业绩情况月度统计</span>
          </div>
          <el-table :data="tableData4"
            :summary-method="(param) => { return getSummaries(param, '客户经理业绩情况月度统计', [4, 5, 6]) }" max-height="380"
            show-summary :header-cell-style="{ background: '#FAFBFC', color: '#828A9D', textAlign: 'center' }"
            :cell-style="{ textAlign: 'center', color: '#1B2431' }">
            <el-table-column prop="account_manager_name" label="客户经理" show-overflow-tooltip></el-table-column>
            <el-table-column prop="AMTotalContractAmount" label="合同签约总额"></el-table-column>
            <el-table-column prop="AMNumberOfContractedProjects" label="签约项目数"></el-table-column>
            <el-table-column prop="AMNumberOfCancelledProjects" label="取消项目数"></el-table-column>
            <el-table-column prop="AMStatisticalSigningRate" label="签约率">
              <template slot-scope="scope">{{ scope.row.AMStatisticalSigningRate }}%</template>
            </el-table-column>
            <el-table-column prop="AMSigningTimeLimit" label="签约时效(天)"></el-table-column>
            <el-table-column prop="AMStatisticalDiscountRate" label="折扣率">
              <template slot-scope="scope">{{ scope.row.AMStatisticalDiscountRate }}%</template>
            </el-table-column>
            <el-table-column prop="AMProjectSettlementAmount" label="项目结算数"></el-table-column>
          </el-table>
        </div>
        <div style="width: 401px;display: flex;">
          <div class="line-vertical"></div>
          <div style="width: 360px;">
            <div class="statistics-tips">
              <span class="title">取消项目类型统计</span>
            </div>
            <div class="qxxmlxtj" ref="qxxmlxtj"></div>
          </div>
        </div>
      </div>
    </div>
    <!-- 4 -->
    <div class="item-box">
      <div class="statistics-tips">
        <span class="title">待结算尾款情况统计</span>
      </div>
      <el-table :data="tableData5" :summary-method="getSummaries" show-summary
        :header-cell-style="{ background: '#FAFBFC', color: '#828A9D', textAlign: 'center' }"
        :cell-style="{ textAlign: 'center', color: '#1B2431' }">
        <el-table-column prop="days" label="账期"></el-table-column>
        <el-table-column prop="PTToBeSettledNum" label="普通店项目数"></el-table-column>
        <el-table-column prop="PTToBeSettledAmount" label="普通店总金额"></el-table-column>
        <el-table-column prop="TPToBeSettledNum" label="特批店项目数"></el-table-column>
        <el-table-column prop="TPToBeSettledAmount" label="特批总金额"></el-table-column>
        <el-table-column prop="SubtotalAmount" label="小计"></el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import sApi from "@/api/statisticsApi";
import aApi from "@/api/adminApi";
import { getUserInfo } from '@/utils/auth';

export default {
  name: '',
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          const today = new Date();
          today.setHours(0, 0, 0, 0); // 将时间设置为今天的开始
          return time.getTime() > today.getTime();
        }
      },
      t1loading: false,
      t2loading: false,
      t3loading: false,
      userInfo: '',
      year: '',
      user_manage: '',
      time: '',
      userManageList: [],
      ydqyxmsDemo: null,
      ydqyjeqsDemo: null,
      qxxmlxtjDemo: null,

      t1Data: {
        TotalContractAmount: 0,
        TotalNumberOfSignedProjects: 0,
        MonthlySignedLineChart: {}
      },
      cancelData: [],

      tableData1: [],

      tableData2: [],

      tableData3: [],

      tableData4: [],

      tableData5: [],

      // 定时请求
      times: 60,
      timer: null,
    }
  },
  mounted() {
    this.userInfo = getUserInfo();

    this.getAdminList();
    this.monthlyContractAmountTrend();
    this.realTimeProjectSummary();
    this.t3Promise();
    this.pendingSettlementStatistics();

    this.timer = setInterval(() => {
      this.times -= 1;
      if (this.times <= 0) {
        this.times = 60;
        this.getAdminList();
        this.monthlyContractAmountTrend();
        this.realTimeProjectSummary();
        this.t3Promise();
        this.pendingSettlementStatistics();
      }
    }, 1000);

    window.addEventListener("resize", this.resize);
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer)
    }
    window.removeEventListener("resize", this.resize);
  },
  methods: {
    resize() {
      this.ydqyxmsDemo.resize();
      this.ydqyjeqsDemo.resize();
    },
    yearChange() {
      this.monthlyContractAmountTrend();
    },
    userChange() {
      this.monthlyContractAmountTrend();
    },
    timeChange() {
      this.t3Promise();
    },
    // 月度签约项目数
    ydqyxmsStatistics() {
      let _data = this.t1Data.MonthlySignedLineChart;
      let xAxisData = [];
      let seriesData = [];
      Object.keys(_data).map(key => {
        xAxisData.push(key);
        seriesData.push(_data[key].TotalOrders);
      })
      console.log(JSON.stringify(xAxisData), JSON.stringify(seriesData))
      let element = this.$refs["ydqyxms"];
      let option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
            lineStyle: {
              color: '#3B75FF',
              opacity: 0.04
            }
          }
        },
        grid: {
          top: '5%',
          left: '0%',
          right: '0%',
          bottom: '0%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            axisLine: {
              lineStyle: {
                color: '#DBE4EB',
                type: 'dashed'
              },
            },
            axisLabel: {
              color: '#999999',
              fontSize: 12,
              fontFamily: 'Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, Arial, sans-serif'
            },
            axisTick: {
              show: false
            },
            data: xAxisData,
          }
        ],
        yAxis: {
          type: 'value',
          axisLabel: {
            color: '#999999',
            fontSize: 12,
            fontFamily: 'Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, Arial, sans-serif'
          },
          splitLine: {
            lineStyle: {
              color: '#DBE4EB',
              type: 'dashed'
            },
          },
        },
        series: [
          {
            name: '项目数',
            type: 'bar',
            barWidth: '30px',
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                offset: 0,
                color: '#B6CFFF'
              }, {
                offset: 1,
                color: '#949DFD'
              }])
            },
            data: seriesData
          }
        ]
      };
      let line = echarts.getInstanceByDom(element);
      if (line == null) {
        line = echarts.init(element);
      }
      line.setOption(option, true);
      this.ydqyxmsDemo = line;
    },
    // 月度签约金额趋势
    ydqyjeqsStatistics() {
      let _data = this.t1Data.MonthlySignedLineChart;
      let xAxisData = [];
      let seriesData = [];
      Object.keys(_data).map(key => {
        xAxisData.push(key);
        seriesData.push({
          value: _data[key].TotalAmount == 0 ? 0 : Math.floor(_data[key].TotalAmount / 10) / 100,
          zb: _data[key].AmountRatio
        });
      })
      console.log(JSON.stringify(xAxisData), JSON.stringify(seriesData))
      let count = 1355;
      let element = this.$refs["ydqyjeqs"];
      let option = {
        tooltip: {
          trigger: 'axis',
          formatter: (item) => {
            let html = `
                <div style="font-weight: 700;font-size: 14px;">${item[0].name}</div>
                <div style="display: flex;padding: 5px 0;">
                  <div style="width:10px;height:10px;border-radius:10px;background:#6299FF;margin-top:5px"></div>
                  <div style="margin-left:5px;">
                    <div style="font-size: 12px;color:#384774;">合同签约金额：${item[0].data.value}k</div>
                    <div style="margin-top:5px;font-size: 12px;color:#384774;">合同金额占比：${item[0].data.zb}%</div>
                  </div>
                </div>
              `;
            return html
          }
        },
        grid: {
          top: '5%',
          left: '0%',
          right: '22px',
          bottom: '0%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            axisLine: {
              lineStyle: {
                color: '#EEEEEE',
                type: 'solid'
              },
            },
            axisLabel: {
              color: '#989898',
              fontSize: 12,
              fontFamily: 'Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, Arial, sans-serif'
            },
            axisTick: {
              show: false
            },
            data: xAxisData,
          }
        ],
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value}k',
            color: '#989898',
            fontSize: 12,
            fontFamily: 'Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, Arial, sans-serif'
          },
          splitLine: {
            lineStyle: {
              color: '#EEEEEE',
              type: 'dashed'
            },
          },
        },
        series: [
          {
            name: '签约金额',
            type: 'line',
            stack: 'Total',
            smooth: true,
            showSymbol: false,
            lineStyle: {
              width: 2.5,
              color: '#6299FF',
              shadowColor: 'rgba(98, 153, 255, 0.50)',
              shadowBlur: 9,
              shadowOffsetY: 2
            },
            areaStyle: {
              color: 'rgba(98, 153, 255, 0.08)'
            },
            data: seriesData
          },
        ]
      };

      let line = echarts.getInstanceByDom(element);
      if (line == null) {
        line = echarts.init(element);
      }
      line.setOption(option, true);
      this.ydqyjeqsDemo = line;
    },
    // 取消项目类型统计
    qxxmlxtjStatistics() {
      let total = 0;
      let echartData = [];
      this.cancelData.map(item => {
        let obj = {
          name: item.cancel_type,
          value: item.cancel_num,
        }
        switch (item.cancel_type) {
          case '价格原因':
            echartData[0] = obj
            break;
          case '客户拒绝沟通':
            echartData[1] = obj
            break;
          case '工期原因':
            echartData[2] = obj
            break;
          case '客户自行施工':
            echartData[3] = obj
            break;
          case '客户失联':
            echartData[4] = obj
            break;
          case '不可抗力因素':
            echartData[5] = obj
            break;
          case '其他原因':
            echartData[6] = obj
            break;
          case '前施工问题影响':
            echartData[7] = obj
            break;
        }
        total += item.cancel_num;
      })
      let element = this.$refs["qxxmlxtj"];
      let option = {
        title: {
          text: "取消总数",
          subtext: total + "",
          left: "50%",
          top: "28%",
          padding: [10, 0],
          textStyle: {
            color: "#878C9A",
            fontSize: 14,
            fontWeight: "normal",
            align: "center",
          },
          textAlign: "center",
          subtextStyle: {
            color: "#384774",
            align: "center",
            fontWeight: "normal",
            fontSize: 24,
          },
        },
        tooltip: {
          trigger: "item",
          formatter: '{b} {c}({d}%)'
        },
        legend: {
          width: 280,
          bottom: "0%",
          icon: "circle",
          align: "auto",
          textStyle: {
            rich: {
              uname: {
                width: 'auto',
                fontSize: 12,
                color: "#878C9A",
                padding: [0, 5, 0, 0]
              },
              unum: {
                color: "#384774",
                width: 20,
                align: "right",
                fontSize: 12,
              },
            },
          },
          formatter(name) {
            let value;
            echartData.forEach((item, index) => {
              if (item.name == name) {
                value = item.value;
              }
            });
            return `{uname|${name}}{unum|${value}}`;
          },
        },
        series: [
          {
            type: "pie",
            color: ["#5291FF", "#3AD0BD", "#FEC371", "#FD706D", "#7485E5", "#87CA8B", "#FFA176", "#6CA8F6"],
            center: ["50%", "35%"],
            radius: ["40%", "70%"],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 5,
              borderColor: "#fff",
              borderWidth: 2,
            },
            label: {
              show: false,
              color: "#fff",
            },
            emphasis: {
              label: {
                show: false,
              },
            },
            labelLine: {
              show: false,
            },
            data: echartData,
          },
        ],
      };
      let line = echarts.getInstanceByDom(element);
      if (line == null) {
        line = echarts.init(element);
      }
      line.setOption(option, true);
      this.qxxmlxtjDemo = line;
    },

    getSummaries(param, tableName, labelArr) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return Math.floor((prev + curr) * 100) / 100;
            } else {
              return Math.floor((prev) * 100) / 100;
            }
          }, 0);
          if (tableName == '各类型门店签约情况统计') {
            if (labelArr.includes(index)) {
              sums[index] = Math.floor(sums[index] / data.length * 100) / 100;
              if (index != 7) {
                sums[index] += '%';
              }
            }
          }
          if (tableName == '客户经理业绩情况月度统计') {
            if (labelArr.includes(index)) {
              sums[index] = Math.floor(sums[index] / data.length * 100) / 100;
              if (index != 5) {
                sums[index] += '%';
              }
            }
          }

        } else {
          sums[index] = '--';
        }
      });
      return sums;
    },

    /****************api接口*****************/
    // 获取客户经理
    getAdminList() {
      aApi.getAdminList({
        page: 1,
        num: 99,
        identity: 1,
        position_id_arr: [2],
      }).then(res => {
        console.log(res, 'getAdminList')
        if (res.code == 200) {
          this.userManageList = res.data.list;
        }
      })
    },
    // 获取 1
    monthlyContractAmountTrend() {
      this.t1loading = true;
      sApi.monthlyContractAmountTrend({
        account_manager_id: this.user_manage,
        year: this.year
      }).then(res => {
        console.log(res, '月度签约金额趋势/月度签约项目数')
        if (res.code == 200) {
          this.t1Data = res.data;
          this.ydqyxmsStatistics();
          this.ydqyjeqsStatistics();
          this.t1loading = false;
        }
      })
    },
    // 获取 2
    realTimeProjectSummary() {
      this.t2loading = true;
      sApi.realTimeProjectSummary().then(res => {
        console.log(res, '实时项目汇总')
        if (res.code == 200) {
          this.tableData1 = res.data;
          this.t2loading = false;
        }
      })
    },
    // 获取 3
    async t3Promise() {
      this.t3loading = true;
      let search = {};
      let time = this.time;
      if (time) {
        search = {
          start_date: time[0],
          end_date: time[1]
        }
      }
      // 获取 3-1
      let signingStatistics = await sApi.signingStatistics(search);
      console.log(signingStatistics, '签约情况统计')
      if (signingStatistics.code == 200) {
        this.tableData2 = [signingStatistics.data];
      }
      // 获取 3-2
      let storeTypeSigningStatistics = await sApi.storeTypeSigningStatistics(search);
      console.log(storeTypeSigningStatistics, '各类型门店签约情况统计')
      if (storeTypeSigningStatistics.code == 200) {
        this.tableData3 = storeTypeSigningStatistics.data;
      }
      // 获取 3-3
      let accountManagersMonthlyPerformance = await sApi.accountManagersMonthlyPerformance(search);
      console.log(accountManagersMonthlyPerformance, '客户经理业绩情况月度统计')
      if (accountManagersMonthlyPerformance.code == 200) {
        this.tableData4 = accountManagersMonthlyPerformance.data;
      }
      // 获取 3-4
      let cancelTypeStatistics = await sApi.cancelTypeStatistics(search);
      console.log(cancelTypeStatistics, '取消项目类型统计')
      if (cancelTypeStatistics.code == 200) {
        this.cancelData = cancelTypeStatistics.data;
        this.qxxmlxtjStatistics();
      }
      this.t3loading = false;
    },
    // 获取 4
    pendingSettlementStatistics() {
      sApi.pendingSettlementStatistics().then(res => {
        console.log(res, '待结算尾款情况统计')
        if (res.code == 200) {
          this.tableData5 = res.data;
        }
      })
    }

  },
}
</script>

<style lang='scss' scoped>
@import './index.scss';
</style>
